//jqGrid的配置信息
$.jgrid.defaults.width = 1000;
$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

//工具集合Tools
window.T = {
    //
    selectLayer:function (selectUrl,tableList,tableId,pagerId) {
        $("#"+ tableId).jqGrid({
            url: baseURL + selectUrl,
            datatype: "json",
            colModel:tableList,
            viewrecords: true,
            height:385,
            rowNum: 10,
            rowList : [10,30,50],
            rownumbers: true,
            rownumWidth: 25,
            multiselect: true,
            pager: "#"+pagerId,
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order"
            },
            gridComplete:function(){
                //隐藏grid底部滚动条
                $("#" + tableId).closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            }
        });
    },
    getSelectedRow:function getSelectedRow(tableId) {
    var grid = $("#" + tableId);
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
        alert("请选择一条记录");
        return;
    }

    var selectedIDs = grid.getGridParam("selarrrow");
    if(selectedIDs.length > 1){
        alert("只能选择一条记录");
        return ;
    }

    return grid.jqGrid('getRowData',selectedIDs[0]);
}

};

// 获取请求参数
// 使用示例
// location.href = http://localhost/index.html?id=123
// T.p('id') --> 123;
var url = function(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
};
T.p = url;

//请求前缀
var baseURL = "/";

//登录token
var token = localStorage.getItem("token");
if(token == 'null'){
    parent.location.href = baseURL + 'login.html';
}

//jquery全局配置
$.ajaxSetup({
	dataType: "json",
	cache: false,
    headers: {
        "token": token
    },
    // xhrFields: {
    //     withCredentials: true
    // },
    complete: function(xhr) {
        //token过期，则跳转到登录页面
        if(xhr.responseJSON.code == 401){
            parent.location.href = baseURL + 'login.html';
        }
    }
});

//jqgrid全局配置
$.extend($.jgrid.defaults, {
    ajaxGridOptions : {
        headers: {
            "token": token
        }
    }
});

//权限判断
function hasPermission(permission) {
    if (window.parent.permissions.indexOf(permission) > -1) {
        return true;
    } else {
        return false;
    }
}

//重写alert
window.alert = function(msg, callback){
	parent.layer.alert(msg, function(index){
		parent.layer.close(index);
		if(typeof(callback) === "function"){
			callback("ok");
		}
	});
}

//重写confirm式样框
window.confirm = function(msg, callback){
	parent.layer.confirm(msg, {btn: ['确定','取消']},
	function(){//确定事件
		if(typeof(callback) === "function"){
			callback("ok");
		}
	});
}


//选择一条记录
function getSelectedRow() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    
    var selectedIDs = grid.getGridParam("selarrrow");
    if(selectedIDs.length > 1){
    	alert("只能选择一条记录");
    	return ;
    }
    
    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    
    return grid.getGridParam("selarrrow");
}

/*3.用正则表达式实现html转码*/
function htmlEncodeByRegExp(str){
    var s = "";
    if(str.length == 0) return "";
    s = str.replace(/&/g,"&amp;");
    s = s.replace(/</g,"&lt;");
    s = s.replace(/>/g,"&gt;");
    s = s.replace(/ /g,"");
    s = s.replace(/\'/g,"&#39;");
    s = s.replace(/\"/g,"&quot;");
    s = s.replace(/\n"/g,"");
    s = s.replace(/\r"/g,"");
    return s;
}
/*4.用正则表达式实现html解码*/
function htmlDecodeByRegExp (str){
    var s = "";
    if(str.length == 0) return "";
    s = str.replace(/&amp;/g,"&");
    s = s.replace(/&lt;/g,"<");
    s = s.replace(/&gt;/g,">");
    s = s.replace(/&nbsp;/g," ");
    s = s.replace(/&#39;/g,"\'");
    s = s.replace(/&quot;/g,"\"");
    return s;
}
//日期格式化，运算方法
Date.prototype.ToString = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
Date.prototype.AddMonths = function (m) {
    var temp = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    temp.setMonth(temp.getMonth() + m);
    return temp;
}
Date.prototype.AddDays = function (d) {
    var temp = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    temp.setDate(temp.getDate() + d);
    return temp;
}
Date.prototype.AddHours = function (h) {
    var temp = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    temp.setHours(temp.getHours() + h);
    return temp;
}
Date.prototype.AddMinutes = function (m) {
    var temp = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    temp.setMinutes(temp.getMinutes() + m);
    return temp;
}
String.prototype.ToDate = function () {
    var splitChar = '-';
    if (this.indexOf('-') > 0) {
        splitChar = '-';
    }
    else if (this.indexOf('/') > 0) {
        splitChar = '/';
    }
    var tempStrs = this.split(" ");
    var dateStrs = tempStrs[0].split(splitChar);
    var year = parseInt(dateStrs[0], 10);
    var month = parseInt(dateStrs[1], 10) - 1;
    var day = parseInt(dateStrs[2], 10);
    var hour = 0;
    var minute = 0;
    var second = 0;
    if ($.trim(tempStrs[1]) != "") {
        var timeStrs = tempStrs[1].split(":");
        var hour = parseInt(timeStrs[0], 10);
        var minute = parseInt(timeStrs[1], 10) - 1;
        var second = parseInt(timeStrs[2], 10);
    }
    return new Date(year, month, day, hour, minute, second);
}

//判断一个数组中的某一个值是否存在，存在返回相应的位置否则返回-1；
function arrIndexOf(arr,aValue){
    for(var i=0;i<arr.length;i++){
        if(arr[i]==aValue){
            return i;
        }
    }
    return -1;
}

/*方法*/
function removeClass(obj, sClassName) {
    var arr = obj.className.split(" ");
    if (arrIndexOf(arr, sClassName) != -1) {
        arr.splice(arrIndexOf(arr, sClassName), 1);
        obj.className=arr.join(" ");
        //删除这个类名并将整个类名组重新转为字符串
    }
}


function addClass(obj, className) {

    if (obj.className == "") {
        obj.className = className;
    } else {
        var arr = obj.className.split(" ");//利用class间的空格将其拆分为数组
        if (arrIndexOf(arr, className) == -1) {//这个元素里面已经存在另外的class的判断
            obj.className += " " + className;
        }
    }
}

